<template>
  <el-table
    header-row-class-name="base-table-header-v3"
    row-class-name="base-table-row-v3"
    :data="data"
    :border="border">
    <el-table-column
      v-for="(column, index) in colums"
      :key="`${column.fieldName}_${index}`"
      :label="column.displayName"
      :prop="column.fieldName"
      show-overflow-tooltip
      :width="column.width">
      <template slot-scope="scope">

        <!-- start 备件名称 -->
        <template v-if="column.fieldName === 'name'">
          <template v-if="canSelectPart" class="search-in-part">
            <biz-remote-select
              :placeholder="$t('common.placeholder.select')"
              :value="[scope.row]"
              :remote-method="fetchSparepart"
              @input="choosePart($event, scope.row, scope.$index)"
            >
              <div class="search-in-part-item"  slot="option" slot-scope="{ option }">
                <template v-if="option.name && !loading">
                  <p>{{$t('common.base.name')}}：<span>{{ option.name }}</span></p>
                  <p>{{$t('common.base.serialNumber')}}：<span>{{ option.serialNumber }}</span></p>
                  <p>{{$t('common.base.type')}}：<span>{{ option.type }}</span></p>
                  <p>{{$t('common.form.preview.sparepart.label3')}}：<span>{{ option.standard }}</span></p>
                  <p v-if="option.description">{{$t('common.form.preview.sparepart.label5')}}<span>{{option.description}}</span></p>
                  <p v-if="initData.openSuperCodePro && option.productTypeList && option.productTypeList.length != 0">{{$t('common.form.type.related_catalog')}}:
                    <span>
                      {{
                        option.productTypeList &&
                        option.productTypeList.map(i => (i && i.catalogName) || '').join('，')
                      }}
                    </span>
                  </p>
                </template>
                <p class="no_empty" v-else>{{ loading ? $t('common.base.loading') : $t('common.base.tip.noData') }}</p>
              </div>
            </biz-remote-select>
          </template>
          <template v-else>{{ scope.row[column.fieldName] }}</template>
        </template>
        <!-- end 备件名称 -->

        <!-- start 申请仓库 -->
        <template v-else-if="column.fieldName === 'repertory'">
          <el-select
            @change="chooseRepertory($event, scope.row)"
            v-model="scope.row.repertory"
            value-key="repertoryId"
            filterable>
            <el-option
              v-for="item in scope.row.repertorys"
              :key="item.repertoryId"
              :label="item.repertoryName"
              :value="item">
            </el-option>
          </el-select>
        </template>
        <!-- end 申请仓库 -->

        <!-- start 小计 -->
        <template v-else-if="column.fieldName === 'total'">
          <span>
            <span>{{ scope.row.salePrice && (scope.row.preNum * scope.row.salePrice).toFixed(2) }} </span>
            <span v-if="internationalGray && !tableType">{{scope.row.salePriceCurrency || 'CNY'}}</span>
          </span>
        </template>
        <!-- end 小计 -->

        <!-- start 备件&服务项目修改单价 -->
        <template v-else-if="column.fieldName === 'salePrice'">
          <div>
            <div v-if="editUnitPrice">
              <input type="number" :class="internationalGray ? 'sale-price-edit' : 'service-number-input'" v-model="scope.row.salePrice" @change="handleSalePrice(scope.row)" />
              <el-select 
                v-if="internationalGray && !tableType"
                v-model="scope.row.salePriceCurrency" 
                class='sale-price-select'
                :placeholder="$t('common.placeholder.select')">
                <el-option
                  v-for="item in currencyOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  >
                </el-option>
              </el-select>
            </div>
            <div v-else>
              <span v-if="tableType">{{ scope.row.salePrice }}</span> 
              <span v-else> {{ scope.row | fmt_salePrice_currency }}</span> 
            </div>
          </div>
        </template>
        <!-- end 单价 -->

        <!-- start 预计用量 -->
        <template v-else-if="column.fieldName === 'preNum'">
          <input type="number" v-model="scope.row.preNum" @change="handlePreNum(scope.row)" />
        </template>
        <!-- end 预计用量 -->

        <!-- start 操作 -->
        <template v-else-if="column.fieldName === 'action'">
          <el-button class="text-danger" type="text" size="mini" @click="data.splice(scope.$index, 1)">{{$t('common.base.delete')}}</el-button>
        </template>
        <!-- end 操作 -->

        <template v-else>{{ scope.row[column.fieldName] }}</template>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi';
/* util */
import MathUtil from '@src/util/math';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
import { currencyOption } from '@src/util/currency'
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default {
  name: 'part-service-table',
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    colums: {
      type: Array,
      default: () => ([])
    },
    border: {
      type: Boolean,
      default: false
    },
    // 可选择备件
    canSelectPart: {
      type: Boolean,
      default: false
    },
    // 备件配置
    partConfig: {
      type: Object,
      default: () => ({})
    },
    // 物料配置
    materConfig: {
      type: Object,
      default: () => ({})
    },
    type: {
      type: String,
      default: ''
    },
    card: {
      type: Object,
      default: () => ({})
    },
    // 是否可以修改单品价格
    editUnitPrice: {
      type: Boolean,
      default: false
    },
    tableType: {
      type: String,
      default: ''
    }
  },
  inject: ['initData'],
  data() {
    return {
      emptyData: {
        serialNumber: '',
        salePrice: '',
        preNum: '',
        name: '',
        sort: '',
        unit: '',
        id: '',
        relationStandard: ''
      },
      loading: false,
      internationalGray,
      currencyOption
    }
  },
  computed: {
    showRepertory() {
      let idx = this.colums.findIndex(item => item.fieldName == 'repertory')
      return idx > -1;
    }
  },
  methods: {
    /**
     * @description 添加一条表格数据
    */
    add() {
      if (this.data.length > 99) {
        return this.$message({
          showClose: true,
          message: this.$t('task.tip.addSparePartTip2', {max: 100}),
          type: 'error'
        })
      }

      this.data.push({...this.emptyData});
    },
    /**
     * @description 搜索备件
    */
    async fetchSparepart(params) {
      this.loading = true;
      const { keyword, pageNum, pageSize } = params
      try {
        let model = {
          keyWord: keyword,
          pageNum,
          pageSize,
          enable: 1,
          cardId: this.card.cardId
        }
       let res = await TaskApi.getSparePartByUserTagList(model);
        this.loading = false;
        if (!res.success) return;
        res.result.list = res.result.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            ...item,
          }
        });

        return res.result;
      } catch (error) {
        this.loading = false;
        console.warn('fetchSparepart -> error', error);
      } 
    },
    /**
     * @description 选择备件
    */
    choosePart(value, row, index) {
      let selectedPart = value?.[0] || {};
      if(!selectedPart.id) return;
      
      // 判断当前选择的备件是否已经存在, 排除本身
      let idx = this.data.findIndex(item => item.id == selectedPart.id);
      if(idx > -1 && idx != index) return this.$platform.toast(this.$t('task.tip.chooseMaterialTip'), 'warning');

      Object.keys(this.emptyData).forEach(key => {
        if (key == 'preNum') {
          row[key] = 1;
        } else if(key == 'sort') {
          row[key] = selectedPart.type || '';
        } else if(key == 'relationStandard'){
          row[key] = selectedPart.standard || '';
        }else {
          row[key] = selectedPart[key];
        }
      })

      // 获取备件可用仓库列表
      if (this.showRepertory) this.getRepertoryBySparePartIds([selectedPart.id]);
    },

    // 修改单价
    handleSalePrice(item) {
      let value = Number(item.salePrice);
      let count = MathUtil.decimalNumber(value);
      let oldPrice = item.oldPrice ? item.oldPrice : 0;

      if(value < 0){
        this.$platform.alert('请输入不小于0的数值');
        item.salePrice = oldPrice;
        return;
      }

      if(count > 2) {
        this.$platform.alert('最多只能输入2位小数');
        item.salePrice = oldPrice;
        return;
      }
    },
    
    /**
    * @description 修改预计用量
    */
    handlePreNum(item) {
      if (this.type == 'service') return this.handleServiceNum(item);
      return this.handleSparepartNum(item);
    },
    /**
    * @description 修改服务项目预计用量
    */
    handleServiceNum(item) {
      let value = Number(item.preNum);
      let count = MathUtil.decimalNumber(value);
      let max = PART_SERVICE_LIST_PRENUM_MAX_LENGTH;

      if (value <= 0) {
        this.$platform.alert(this.$t('task.tip.rightNumTip'));
        item.preNum = 1;
        return;
      }

      if (value > max) {
        this.$platform.alert(this.$t('task.tip.serviceTip2', {max}));
        item.preNum = max;
        return;
      }

      if (count > 2) {
        this.$platform.alert(this.$t('task.tip.twoDigitalTip'));
        item.preNum = 1;
      }
    },
    /**
    * @description 修改备件预计用量
    */
    handleSparepartNum(item) {
      let value = Number(item.preNum);
      let count = this.decimalNumber(value);
      let max = item.repertoryCount || PART_SERVICE_LIST_PRENUM_MAX_LENGTH;
      let min = max ? (max > 1 ? 1 : max) : 1;

      if (value <= 0) {
        this.$platform.alert(this.$t('task.tip.rightNumTip'));
        item.preNum = min;
        return;
      }

      if (value > max) {
        this.$platform.alert(this.$t('task.tip.serviceTip2', {max}));
        item.preNum = max;
        return;
      }
      
      if (count != -1 && count == 0) {
        this.$platform.alert(this.$t('task.tip.greaterThanZeroTip1'));
        item.preNum = min;
        return;
      }
      
      if (count != -1 && count != 0) {
        this.$platform.alert(this.$t('task.tip.greaterThanZeroTip2', {count}));
        item.preNum = min;
      }
    },
    /**
    * @description 预计用量小数位
    */
    decimalNumber(num) {
      let { sparepart2, precision } = this.partConfig;
      let count = MathUtil.decimalNumber(num);

      if(!sparepart2 && count != 0) return 0;
      if(precision >= count) return -1;
      return precision;
    },
    /**
    * @description 选择仓库
    */
    chooseRepertory(value, row) {
      row.repertoryId = value.repertoryId;
      row.repertoryCount = value.repertoryCount;
    },
    /**
    * @description 获取所有具有该备件的仓库，以及个人库用量
    */
    getRepertoryBySparePartIds(ids) {
      TaskApi.getRepertoryBySparePartIds(ids)
        .then(res => {
          if (res.success) {
            res.result.map(part => {
              let idx = this.data.findIndex(item => item.id == part.id);
              if (idx > -1) {
                // 可申请仓库列表
                let repertorys = part.baseRepertorySpareparts || [];
                repertorys.forEach(item => {
                  item.repertoryName = item?.baseRepertory.name || '';
                })

                this.$set(this.data[idx], 'repertorys', repertorys);
                this.$set(this.data[idx], 'personRepertoryCount', part?.baseUserSparepart?.repertoryCount || 0);

                // 仓库只有一个时默认选中
                let repertory = repertorys.length == 1 ? repertorys[0] : {};
                this.$set(this.data[idx], 'repertory', repertory);
                this.chooseRepertory(repertory, this.data[idx]);
              }
            })
          }
        }).catch(err => console.error(err))
    },
  }
}
</script>

<style lang="scss">
  .search-in-part-item {
    padding: 8px 5px 8px 0;
    overflow: hidden;
    max-width: 260px;
    p {
      /*@include text-ellipsis();*/
      line-height: 20px;
      margin: 0 16px 0 0;
      // color: $text-color-primary;
      white-space: initial;
      span {
        // color: $text-color-regular;
      }
    }

    .no_empty {
      padding: 0;
      text-align: center;
      color: #999;
      font-size: 14px;
    }
  }
</style>

<style lang="scss" scoped>
input[type="number"],
.el-autocomplete {
  width: 99%;
}
.service-number-input {
  width: 99%;
}
.sale-price-edit {
  width: 50%!important;
}
.sale-price-select {
  width: 50%;
}
.el-table {
  &::before {
    content: "";
  }
}
</style>